<template>
    <div class="add-goods">
        <cu-header-add/>
        <div class="add-form">
            <div class="form">
                <el-form ref="form" :model="form" :rules="rules" label-width="200px">
                    <p class="title"></p>
                    <el-form-item :label="$t('component.addGoods.2')" prop="name">
                        <el-input type="text" maxlength="1000"  v-model="form.name" :placeholder="$t('component.addGoods.3')" show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('component.addGoods.4')" prop="type">
                        <el-cascader v-model="form.type" :options="typeList" :props="{ value: 'id', label: 'showName', children: 'categoryList' }" :placeholder="$t('component.addGoods.5')" @change="handleMultiTypeChange" style="width: 100%"></el-cascader>
                    </el-form-item>

                    <p class="title"></p>
                    <el-form-item >
                        <el-button-group style="display:flex;align-items:center">
                            <el-button :type="form.dealType == 0 ? 'primary' : 'default'" @click="handleDealType(0)">{{ $t('component.addGoods.9') }}</el-button>
                            <el-button :type="form.dealType == 1 ? 'primary' : 'default'" @click="handleDealType(1)">{{ $t('component.addGoods.10') }}</el-button>
                        </el-button-group>
                    </el-form-item>
                    <!-- :label="$t('component.addGoods.8')" -->
                    <el-form-item  v-if="form.dealType == 0">
                        <el-input :placeholder="$t('component.addGoods.11')" @change="priceFilter" @focus="clearFilter" v-model="form.price" style="width: 190px;">
                            <span v-if="form.price" slot="suffix" class="el-input__span">kz</span>
                        </el-input>
                        <!-- <span v-if="form.price" style="margin: 0 0 0 20px;font-size:18px;color:red">{{form.price | num2Money}} KZ</span> -->
                    </el-form-item>
                    <el-form-item :label="$t('component.addGoods.12')">
                        <el-radio-group v-model="form.faceToFace" style="margin-top:-15px">
                            <el-radio :label="'1'">{{ $t('component.addGoods.13') }}</el-radio>
                            <el-radio :label="'0'">{{ $t('component.addGoods.14') }}</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <p class="title"></p>
                    <el-form-item v-for="item in typeParams" :label="item.typeParam.portugalName" :key="item.typeParam.id">
                        <el-select v-if="item.typeParam.type=='select'" v-model="item.typeParam.value" :placeholder="$t('component.addGoods.5')">
                            <el-option v-for="meta in item.paramValues" :key="meta.id" :label="meta.portugalName" :value="meta.id"> </el-option>
                        </el-select>
                        <el-input style="width:200px" v-else v-model="item.typeParam.value"></el-input>
                    </el-form-item>

                    <p class="title" v-if="typeParams.length>0"></p>

                    <el-form-item :label="$t('component.addGoods.6')" prop="des" style="min-height:250px">
                        <quill-editor
                           style="height:200px"
                            v-model="form.des"
                            ref="myQuillEditor"
                            :options="editorOption">
                        </quill-editor>
                        <!-- <el-input type="textarea" maxlength="2000" show-word-limit :rows="10" v-model="form.des" :placeholder="$t('component.addGoods.7')"></el-input> -->
                    </el-form-item>

                    <p class="title"></p>

                    <!-- :label="$t('component.addGoods.8')" -->

<!--                    <el-row :gutter="20" type="flex" class="row-bg" justify="space-between">-->
<!--                        <el-col :span="16">-->
<!--                            <div class="grid-content bg-purple">-->
<!--                                <el-form-item :label="$t('component.addGoods.8')">-->
<!--                                    <el-col :span="10">-->
<!--                                        <el-button-group style="display:flex;align-items:center">-->
<!--                                            <el-button :type="form.dealType == 0 ? 'primary' : 'default'" @click="handleDealType(0)">{{ $t('component.addGoods.9') }}</el-button>-->
<!--                                            <el-button :type="form.dealType == 1 ? 'primary' : 'default'" @click="handleDealType(1)">{{ $t('component.addGoods.10') }}</el-button>-->
<!--                                        </el-button-group>-->
<!--                                    </el-col>-->
<!--                                    <el-col :span="12" :offset="2" v-if="form.dealType == 0">-->
<!--                                        <el-input :placeholder="$t('component.addGoods.11')" v-model="form.price">-->
<!--                                            <span slot="suffix" class="el-input__span">kz</span>-->
<!--                                        </el-input>-->
<!--                                    </el-col>-->
<!--                                </el-form-item>-->
<!--                            </div>-->
<!--                        </el-col>-->
<!--                        <el-col :span="8">-->
<!--                            <div class="grid-content bg-purple-light">-->
<!--                                <el-form-item :label="$t('component.addGoods.12')">-->
<!--                                    <el-radio-group v-model="form.faceToFace">-->
<!--                                        <el-radio label="1">{{ $t('component.addGoods.13') }}</el-radio>-->
<!--                                        <el-radio label="0">{{ $t('component.addGoods.14') }}</el-radio>-->
<!--                                    </el-radio-group>-->
<!--                                </el-form-item>-->
<!--                            </div>-->
<!--                        </el-col>-->
<!--                    </el-row>-->

<!--                    <p class="title"></p>-->
                    <el-form-item :label="$t('component.addGoods.15')" prop="imgList">
                        <el-upload class="avatar-uploader" :action="uploadUrl" list-type="picture-card" :file-list="uploadList" :on-remove="handleRemove" :on-success="handleAvatarSuccess">
                            <div class="avatar-add">
                                <i class="el-icon-plus avatar-uploader-icon"></i>
                                <span class="avatar-uploader-tip">{{ $t('component.addGoods.35') }}</span>
                            </div>
                        </el-upload>
                    </el-form-item>

                    <!-- <p class="title">{{ $t('component.addGoods.1') }}</p> -->
                    <p class="title"></p>
                    <!-- <el-form-item :label="$t('component.addGoods.16')" prop="telephone">
                        <el-input type="text" v-model="form.telephone" :placeholder="$t('component.addGoods.17')"></el-input>
                    </el-form-item>
                    <el-form-item label="Caixa de correio" :prop="$t('component.addGoods.18')">
                        <el-input type="text" v-model="form.email" :placeholder="$t('component.addGoods.19')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('component.addGoods.22')">
                        <el-input type="text" v-model="form.address" :placeholder="$t('component.addGoods.23')"></el-input>
                    </el-form-item> -->
                    <el-form-item :label="$t('component.addGoods.20')" prop="area">
                        <el-cascader ref="area" v-model="form.area" :options="multiOptions" :props="{ value: 'code', label: 'name' }" :placeholder="$t('component.addGoods.21')" @change="handleMultiChange" style="width: 100%"></el-cascader>
                    </el-form-item>
                    <!-- <el-form-item>
                        <div class="map" ref="map" style="width: 100%; height: 500px"></div>
                    </el-form-item> -->
                    <div style="text-align: center;padding-bottom: 30px">
                        <el-button type="default" @click="goBack">{{ $t('component.addGoods.24') }}</el-button>
                        <el-button type="primary" @click="handleSubmit">{{ $t('component.addGoods.25') }}</el-button>
                    </div>
                </el-form>
            </div>
        </div>
        <cu-footer/>
    </div>
</template>

<script>
    import Api from '@/api';

    import Vue from 'vue';
    import { Domain, MAPKEY } from '@/constants';
    import { isEmail } from '@/utils';
    import { Loader } from '@googlemaps/js-api-loader';
    import CuFooter from "../components/footer/index";
    import CuHeaderAdd from "../components/header-add/index";
    import { quillEditor } from "vue-quill-editor"; //调用编辑器
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';

    export default {
        name: 'AddGoods',
        components: {CuHeaderAdd, CuFooter,quillEditor},
        data() {
            return {
                domain: Domain,
                uploadUrl: Api.uploadUrl,
                map: null,
                form: {
                    name: '',
                    type: '',
                    area: '',
                    des: '',
                    price: '',
                    imgList: '',
                    telephone: '',
                    email: '',
                    address: '',
                    faceToFace: '0',
                    dealType: 0,
                    latitude: '',
                    longitude: '',
                    areaName: '',
                    parameterList: '',
                },
                goods: {},
                rules: {
                    avatar: { required: true, message: window.$lang.t('component.addGoods.26'), trigger: 'change' },
                    name: { required: true, message: window.$lang.t('component.addGoods.27'), trigger: 'blur' },
                    des: { required: true, message: window.$lang.t('component.addGoods.28'), trigger: 'blur' },
                    telephone: { required: true, message: window.$lang.t('component.addGoods.29'), trigger: 'blur' },
                    email: [
                        { required: true, message: window.$lang.t('component.addGoods.30'), trigger: 'blur' },
                        {
                            validator: (rule, value, callback) => {
                                if (!isEmail(value)) {
                                    callback(new Error(window.$lang.t('component.addGoods.31')));
                                } else {
                                    callback();
                                }
                            },
                            trigger: 'blur',
                        },
                    ],
                    type: { required: true, message: window.$lang.t('component.addGoods.32'), trigger: 'change' },
                    area: { required: true, message: window.$lang.t('component.addGoods.33'), trigger: 'change' },
                },
                typeParams: [],
                paramsValue: [],
                multiOptions: [],
                typeList: [],
                uploadList: [],
                editorOption:{
                    placeholder: this.$t('component.addGoods.7'),
                    modules:{
                           toolbar:'',
                    }

                }
            };
        },
        //  computed: {
        //     priceFilter: {
        //         get() {
        //             let temp = Vue.filter('num2Money');
        //             return temp(this.form.price)
        //         },
        //         set(val) {
        //             this.form.price = val
        //         }
        //     }
        // },
        created() {
            this.loadTree();
            this.loadType();

            if (this.$route.params.id) {
                Api.goodsDetail({id:this.$route.params.id}).then(resp => {
                    this.goods = resp
                    this.form = this.goods;
                    this.form.area = this.goods.areaCode.split('/');
                    this.form.area.splice(0,1)
                    this.form.area.splice(this.form.area.length-1,1)
                    this.priceFilter()
                    this.form.type = [this.goods.sectionId, this.goods.categoryId];
                    if (this.goods.categoryId){
                        Api.typeParamsList({ typeId: this.goods.categoryId }).then((res) => {
                            this.typeParams = res;
                            //回显参数
                            const values = JSON.parse(this.goods.parameterList)
                            if (values.length>0){
                                values.forEach(meta => {
                                    if (meta.id){
                                        this.typeParams.find(item => item.typeParam.portugalName==meta.portugalName).typeParam.value=meta.id
                                    }else {
                                        // this.typeParams.find(item => item.portugalName==meta.portugalName)
                                        this.typeParams.find(item => item.typeParam.portugalName==meta.portugalName).typeParam.value=meta.portugalNameInner
                                    }
                                })
                            }
                        });
                    }
                    const imgs = JSON.parse(this.goods.imgList);
                    this.uploadList = imgs.map((item) => {
                        return {
                            path: item,
                            url: Domain + item,
                        };
                    });
                })

            } else {
                this.loadUserInfo();
            }
        },
        mounted() {
            this.initMap();
        },
        methods: {
            clearFilter(val){
                this.form.price = this.form.price.replace(/,/g,'')

            },
            priceFilter(val){
                let temp = Vue.filter('num2Money');
                this.form.price = Number(this.form.price).toFixed(0).toString()
                this.form.price = temp(this.form.price)
            },
            goBack(){
                this.$router.go(-1)
            },
            initMap() {
                const mapLoader = new Loader({
                    apiKey: MAPKEY,
                    version: 'weekly',
                });
                mapLoader.load().then(async () => {
                    const position = await this.getPosition();
                    this.map = new window.google.maps.Map(this.$refs.map, {
                        center: position,
                        zoom: 8,
                    });
                    let marker = null;
                    this.map.addListener('click', (mapsMouseEvent) => {
                        if (marker) {
                            marker.setMap(null);
                        }
                        this.form.latitude = mapsMouseEvent.latLng.lat();
                        this.form.longitude = mapsMouseEvent.latLng.lng();
                        marker = new window.google.maps.Marker({
                            position: mapsMouseEvent.latLng,
                            map: this.map,
                        });
                    });
                });
            },
            getPosition() {
                return new Promise((resolve) => {
                    if (navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(
                            (position) => {
                                const { latitude, longitude } = position.coords;
                                resolve({
                                    lat: latitude,
                                    lng: longitude,
                                });
                            },
                            () => {
                                resolve({
                                    lat: 0,
                                    lng: 0,
                                });
                            }
                        );
                    } else {
                        resolve({
                            lat: 0,
                            lng: 0,
                        });
                    }
                });
            },
            loadUserInfo() {
                Api.loadUser().then((res) => {
                    this.form.email = res.email;
                    this.form.telephone = res.mobile;
                });
            },
            handleAvatarSuccess(response, file, fileList) {
                this.uploadList.push({
                    path: response.path,
                    url: Domain + response.path,
                });
            },
            handleRemove(file, fileList) {
                const index = this.uploadList.findIndex((item) => item.path === file.path);
                this.uploadList.splice(index, 1);
            },
            handleMultiChange(value) {
                console.log(value)
                // const address = this.$refs.area.getCheckedNodes()[0].pathLabels.join('');
                this.form.area = value;
                this.form.areaName = this.$refs.area.getCheckedNodes()[0].pathLabels.join('/');
                // 逆地理位置解析
                // axios({
                //   url: 'https://maps.googleapis.com/maps/api/geocode/json',
                //   method: 'get',
                //   params: {
                //     address: address,
                //     key: MAPKEY,
                //   },
                // }).then((res) => {
                //   if (res.status === 200) {
                //     const { status, results, error_message } = res.data;
                //     if (status === 'OK') {
                //       this.form.latitude = results[0].geometry.location.lat;
                //       this.form.longitude = results[0].geometry.location.lng;
                //     } else {
                //       console.log(error_message);
                //     }
                //   }
                // });
            },
            handleMultiTypeChange(value) {
                this.form.type = value;
                Api.typeParamsList({ typeId: value[1] }).then((res) => {
                    this.typeParams = res;
                    console.log(this.typeParams)
                });
            },
            handleDealType(type) {
                this.form.dealType = type;
            },
            loadTree() {
                Api.areaTree().then((res) => {
                    this.multiOptions = res;
                });
            },
            loadType() {
                Api.goodsTypeList().then((res) => {
                    this.typeList = res;
                });
            },
            handleSubmit() {

                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        this.form.areaCode = '/' + this.form.area.join('/') + '/';
                        const section = this.typeList.find((item) => item.id == this.form.type[0]);
                        this.form.sectionId = section.id;
                        this.form.sectionName = section.showName;
                        const category = section.categoryList.find((item) => item.id == this.form.type[1]);
                        this.form.categoryId = category.id;
                        this.form.categoryName = category.showName;
                        if(this.form.price){
                            this.form.price = this.form.price.replace(/,/g,'')
                        }
                        if (this.typeParams.length > 0) {
                            let arr = []
                            this.typeParams.forEach((item,index)=>{
                                if (item.typeParam.value){
                                    let obj = {}
                                    if (item.typeParam.type=='select'){
                                        obj.chinaName = item.typeParam.chinaName
                                        obj.englishName = item.typeParam.englishName
                                        obj.portugalName = item.typeParam.portugalName
                                        item.paramValues.forEach((inner,index)=>{
                                            if(item.typeParam.value === inner.id){
                                                obj.chinaNameInner = inner.chinaName
                                                obj.englishNameInner = inner.englishName
                                                obj.portugalNameInner = inner.portugalName
                                                obj.id = inner.id
                                            }
                                        })
                                    }else {
                                        obj.chinaName = item.typeParam.chinaName
                                        obj.englishName = item.typeParam.englishName
                                        obj.portugalName = item.typeParam.portugalName
                                        obj.chinaNameInner = item.typeParam.value
                                        obj.englishNameInner = item.typeParam.value
                                        obj.portugalNameInner = item.typeParam.value
                                        obj.id = null
                                    }
                                    arr.push(obj)
                                }
                           })
                           this.form.parameterList = JSON.stringify(arr);
                        }
                        const params = {
                            ...this.form,
                            imgList: JSON.stringify(this.uploadList.map((item) => item.path)),
                            area: '',
                            type: '',
                        };
                        if(this.$route.params.id){
                            Api.updateGoods(params).then(() => {
                            this.$emit('success');
                            this.$router.push("/account")
                           });
                        }else{
                           Api.addGoods(params).then(() => {
                            this.$emit('success');
                            this.$router.push("/account")
                           });
                        }

                    } else {
                        return false;
                    }
                });
            },
        },
    };
</script>
<style lang="scss" scoped>

    /* form */
    .add-form {
        background: #f2f2f2;
        border-radius: 4px;
      padding: 30px 15%;
      padding-bottom: 100px;
        .title {
            color: #333;
            font-weight: bold;
            font-size: 16px;
            padding-left: 150px;
            margin-bottom: 20px;
            padding-top: 20px;
            border-top: 1px dashed #e8e8e8;
            margin-top: 40px;
        }
        .form {

            //width: 80%;
          border-radius: 10px;
          padding: 0 5%;
            margin: auto;
          background-color: #fff;
        }
    }
    .avatar-uploader {
       ::v-deep .el-upload-list__item-thumbnail{
            object-fit: cover;
        }
        ::v-deep .el-upload {
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            .avatar-add {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                height: 100%;
                .avatar-uploader-icon {
                    font-size: 28px;
                    color: #8c939d;
                }
                .avatar-uploader-tip {
                    color: #999;
                    font-size: 12px;
                    line-height: 1.5;
                }
            }

            .avatar {
                width: 120px;
                height: 120px;
                display: block;
            }
        }
    }
</style>
